import type { GoodParams, ModifyGoodParams } from '@/services/ant-design-pro/good';
import { addGood, modifyGood } from '@/services/ant-design-pro/good';
import type { UploadProps } from 'antd';
import { Button, Form, Input, InputNumber, Modal, Select, Upload, message } from 'antd';
import ImgCrop from 'antd-img-crop';
import TextArea from 'antd/lib/input/TextArea';
import { useEffect, useState } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { PlusOutlined } from '@ant-design/icons';

type category = {
  value: number;
  label: string;
};
type ModalsParams = {
  type?: number;
  title: string;
  isModalOpen: boolean;
  setIsModalOpen: (value: boolean) => void;
  categoryList: category[];
  initialValues?: ModifyGoodParams;
  init?: () => void;
};

export interface Data {
  content: string;
  coverUrl: string;
  description: string;
  id: number;
  imgs: string[];
  isCollect: boolean;
  isOver: boolean;
  name: string;
  note: string;
  price: number;
  unit: string;
  weight: number;
  [property: string]: any;
}

const unitList = [
  { value: 'kg', label: 'kg' },
  { value: 'g', label: 'g' },
  { value: 'ml', label: 'ml' },
  { value: 'l', label: 'l' },
  { value: '个', label: '个' },
  { value: '件', label: '件' },
  { value: '箱', label: '箱' },
  { value: '盒', label: '盒' },
  { value: '瓶', label: '瓶' },
];

const Modals: React.FC<ModalsParams> = ({
  type = 0,
  title,
  isModalOpen,
  setIsModalOpen,
  categoryList,
  initialValues,
  init,
}) => {
  const [form] = Form.useForm();
  const [coverUrl, setCoverUrl] = useState<any[]>([]); //封面图片上传列表，封面只有一张图片，所以是数组项的第一项
  const [imgs, setImgs] = useState<any[]>([]); //图片相册

  const onChangeUploadCoverUrl: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setCoverUrl(newFileList);
    // console.log('正在上传中');
    // console.log('value', newFileList);
  };

  const onChangeImgs: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setImgs(newFileList);
    console.log(newFileList);
  };

  const handleSubmit = async (values: GoodParams) => {
    let categoryId;
    if (typeof values.channelId === 'string') {
      categoryId = categoryList.find((item) => item.label === values.channelId)?.value;
    } else {
      categoryId = values.channelId;
    }
    // console.log('111', coverUrl, imgs);

    // if (coverUrl.length == 0 || imgs.length == 0) {
    //   message.warning('请上传相应的图片');
    //   return;
    // }
    const params = {
      ...values,
      coverUrl: coverUrl[0]?.response
        ? coverUrl[0]?.response?.data?.url
        : coverUrl[0]
        ? coverUrl[0].url
        : undefined,
      imgs: imgs?.map((item) => {
        if (item.response) {
          return item.response?.data?.url;
        } else {
          return item.url;
        }
      }),
      channelId: categoryId,
    };
    console.log('params', params);
    try {
      const res = await (type === 0
        ? addGood(params)
        : modifyGood({ ...params, id: initialValues?.id as number }));
      if (res.code === 0) {
        message.success(type === 0 ? '商品添加成功' : '商品修改成功');
        init();
        form.resetFields();
      } else {
        message.error(res.msg);
      }
    } catch (error) {
      console.log('添加商品的过程中发生了错误');
    }

    setIsModalOpen(false);
  };

  useEffect(() => {
    console.log('categoryList', categoryList);

    if (initialValues) {
      form.setFieldsValue({
        ...initialValues,
        channelId: categoryList.find((item) => item.value == initialValues.channelId)?.label,
      });
      const imgsArray = Array.isArray(initialValues.imgs)
        ? initialValues.imgs.map((url) => ({ url }))
        : [];
      setImgs(imgsArray);
      // setImgs(initialValues?.imgs?.map((url) => ({ url })));
      // console.log([initialValues.coverUrl]);
      setCoverUrl([{ url: initialValues?.coverUrl }]);
    }
  }, [form, initialValues]);
  return (
    <>
      <Modal
        width="700px"
        title={title}
        open={isModalOpen}
        footer={null}
        onOk={() => setIsModalOpen(false)}
        onCancel={() => setIsModalOpen(false)}
      >
        <Form
          form={form}
          name="add"
          autoComplete="off"
          onFinish={handleSubmit}
          // initialValues={initialValues}
        >
          <Form.Item<GoodParams>
            label="商品名称"
            name="name"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item<GoodParams>
            name="channelId"
            label="商品分类"
            rules={[{ required: true, message: '请选择商品分类' }]}
          >
            <Select style={{ width: 144 }} options={categoryList} />
          </Form.Item>
          <Form.Item<GoodParams>
            name="description"
            label="商品简介"
            //rules={[{ required: true, message: '请输入商品简介' }]}
          >
            <TextArea autoSize={{ minRows: 2, maxRows: 4 }} />
          </Form.Item>
          <Form.Item<GoodParams>
            name="price"
            label="商品价格"
            rules={[{ required: true, message: '请输入商品价格' }]}
          >
            <InputNumber min={0} max={10000} />
          </Form.Item>
          <Form.Item<GoodParams> name="coverUrl" label="封面图片">
            <ImgCrop rotationSlider>
              <Upload
                action="http://114.132.98.212:10010/admin/api/v1/common/upload"
                name="file"
                listType="picture-card"
                maxCount={1}
                fileList={coverUrl}
                onChange={onChangeUploadCoverUrl}
                data={{ type: '1' }}
                headers={{ token: localStorage.getItem('token') }}
              >
                {coverUrl?.length < 1 && <PlusOutlined />}
              </Upload>
            </ImgCrop>
          </Form.Item>
          <Form.Item<GoodParams> name="imgs" label="商品相册">
            <ImgCrop rotationSlider>
              <Upload
                action="http://114.132.98.212:10010/admin/api/v1/common/upload"
                name="file"
                listType="picture-card"
                maxCount={3}
                fileList={imgs}
                onChange={onChangeImgs}
                data={{ type: '2' }}
                headers={{ token: localStorage.getItem('token') }}
              >
                {imgs?.length < 3 && <PlusOutlined />}
              </Upload>
            </ImgCrop>
          </Form.Item>
          <Form.Item<GoodParams>
            name="weight"
            label="商品重量"
            rules={[{ required: true, message: '请输入商品重量' }]}
          >
            <InputNumber min={0} />
          </Form.Item>
          <Form.Item<GoodParams>
            name="unit"
            label="计量单位"
            rules={[{ required: true, message: '请输入商品计量单位' }]}
          >
            <Select style={{ width: 144 }} options={unitList} />
          </Form.Item>
          <Form.Item<GoodParams>
            name="stocks"
            label="商品库存"
            rules={[{ required: true, message: '请输入商品库存' }]}
          >
            <InputNumber min={0} max={10000} />
          </Form.Item>
          <Form.Item<GoodParams>
            name="warnStocks"
            label="商品警告"
            rules={[{ required: true, message: '请输入商品警告' }]}
          >
            <InputNumber min={0} max={10000} />
          </Form.Item>
          <Form.Item<GoodParams>
            name="note"
            label="商品备注"
            //rules={[{ required: true, message: '请输入商品备注' }]}
          >
            <Input />
          </Form.Item>
          {/* <Form.Item<GoodParams>
            name="ordered"
            label="商品排序"
            rules={[
              { required: true, message: '请输入商品排序！' },
              { type: 'number', message: '商品排序必须是数字！' },
            ]}
          >
            <InputNumber min={0} />
          </Form.Item> */}

          <Form.Item<GoodParams>
            name="content"
            label="商品详情"
            //rules={[{ required: true, message: '请输入商品详情' }]}
          >
            <ReactQuill style={{ height: '150px' }} theme="snow" placeholder="请输入商品详情" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              {type === 0 ? '添加' : '修改'}
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default Modals;
